package cn.tworice.admin.web;

import cn.tworice.admin.service.LogService;
import cn.tworice.admin.service.NoticeService;
import cn.tworice.common.entity.Notice;
import cn.tworice.common.entity.dto.NoticeDto;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("admin/notice")
@Slf4j
@CrossOrigin
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private LogService logService;
    /**
     * 获取所有通知
     *
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @GetMapping("list")
    @ApiOperation("获取所有通知")
    public RequestResult list() {
        RequestResult result = new RequestResult();
        List<NoticeDto> list = noticeService.getNoticeList();
        result.setCode(new StatusCode(200, "查询成功"));
        result.appendData("list", list);
        return result;
    }

    /**
     * 添加通知
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @PostMapping("add")
    @ApiOperation("添加通知")
    public RequestResult add(Notice notice, HttpServletRequest request){
        logService.addAdminLog(request.getHeader("adminID"),(notice.getId()==null?"添加":"更新")+"公告信息-"+(notice.getId()==null?"":notice.getId()));

        RequestResult result = new RequestResult();
        int i = noticeService.addNotice(notice);
        if(i==1){
            result.setCode(new StatusCode(200, "操作成功"));
            result.appendData("noticeList",noticeService.getNoticeList());
        }
        return result;
    }

    @DeleteMapping("del")
    @ApiOperation("通过ID删除通知")
    public RequestResult del(String[] ids,HttpServletRequest request){
        RequestResult result = new RequestResult();
        int i=noticeService.rmNoticeById(ids);
        result.setCode(new StatusCode(200,"成功删除"+i+"条通知"));
        result.appendData("noticeList",noticeService.getNoticeList());

        logService.addAdminLog(request.getHeader("adminID"),"删除"+i+"条公告");
        
        return result;
    }

    @PutMapping("setStatus")
    @ApiOperation("设置通知置顶状态")
    public RequestResult setStatus(String id,Integer top,HttpServletRequest request){
        RequestResult result = new RequestResult();
        int i = noticeService.setStatus(id, top);
        if(i==1){
            result.setCode(new StatusCode(200,"设置成功"));

            logService.addAdminLog(request.getHeader("adminID"),(top==1?"设置":"取消")+"置顶公告-"+id);
        }
        return result;
    }
}
